package com.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import java.util.concurrent.TimeUnit;

public class MailServiceImpl implements IMailService {

    @Autowired
    //springboot 封装好的邮箱
    private JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮箱
     * @param to
     */
    @Override
    public void sendMail(String to) {
        String code= RandomUtil.randomString(4); //产生要怎么 并保存到redis
        redisTemplate.boundValueOps(to).set(code);
        redisTemplate.boundValueOps(to).expire(30, TimeUnit.MINUTES);  //MINUTES 分钟

        //发送邮箱
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setFrom(from); //发送
        mailMessage.setTo(to);
        mailMessage.setSubject("验证码注册"); //标题，主题
        mailMessage.setText("你的验证码是："+code);
        javaMailSender.send(mailMessage);
    }


    @Override
    public boolean checkCode(String mail, String code) {
        //从redis 取出验证码
        String redisCode=(String)redisTemplate.boundValueOps(mail).get();
        //判断验证码是否正确
        boolean f=(code!=null && code.equalsIgnoreCase(redisCode));

        if (f){
            //成功要删除原来的
            redisTemplate.boundValueOps(mail).expire(0,TimeUnit.MICROSECONDS);
        }
        return f;
    }
}
